import * as echarts from 'echarts';
import { onBeforeUnmount, onMounted, ref } from 'vue';


export const useEcharts = (option: any, geoJson?: any) => {
    // 地图注册，第一个参数的名字必须和option.geo.map一致
    // echarts.registerMap('china', china)
    if (geoJson && option.geo?.map) {
        echarts.registerMap(option.geo.map, geoJson);
    }

    const chartInstance = ref<echarts.ECharts>(), chartDom = ref();
    const handleResize = () => {
        chartInstance.value?.resize();
    }

    const setOption = (option: any, notMerge?: boolean, lazyUpdate?: boolean) => {
        chartInstance.value?.setOption?.(option, notMerge, lazyUpdate);
    }

    onMounted(() => {
        chartInstance.value = echarts.init(chartDom.value);
        setOption(option);

        window.addEventListener('resize', handleResize);
    })
    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize);
        chartInstance.value?.dispose?.();
    })

    return { chartDom, setOption }
}